package com.zb.nio.channel;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author: zhaobin
 * @date: 2023/12/23 12:39
 * @Description: FileChanel写操作
 */
public class FileChannelDemo2 {
    public static void main(String[] args) throws Exception {
        // FileOutputStream file = new FileOutputStream("001.txt",true);
        RandomAccessFile file = new RandomAccessFile("001.txt","rw");
        FileChannel channel = file.getChannel();

        // 创建buffer，并存入数据
        ByteBuffer buf = ByteBuffer.allocate(1024);
        buf.clear();
        String str = "测试abc" + System.currentTimeMillis();
        buf.put(str.getBytes());
        // 读写转换
        buf.flip();

        // 如果buffer中有数据就写入通道
        while (buf.hasRemaining()){
            channel.write(buf);
        }

        channel.close();
    }
}
